package com.dgz.csmall.product.service.impl;

import com.dgz.csmall.commons.ex.ServiceException;
import com.dgz.csmall.commons.web.ServiceCode;
import com.dgz.csmall.product.dao.persist.repository.BrandCategoryRepository;
import com.dgz.csmall.product.dao.persist.repository.BrandRepository;
import com.dgz.csmall.product.dao.persist.repository.SpuRepository;
import com.dgz.csmall.product.pojo.entity.*;
import com.dgz.csmall.product.pojo.param.BrandAddNewParam;
import com.dgz.csmall.product.pojo.param.BrandUpdateInfoParam;
import com.dgz.csmall.product.pojo.vo.AlbumListItemVO;
import com.dgz.csmall.product.pojo.vo.BrandListItemVO;
import com.dgz.csmall.commons.pojo.vo.PageData;
import com.dgz.csmall.product.pojo.vo.BrandStandardVO;
import com.dgz.csmall.product.service.BrandService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Author duguozheng
 * @Date 2023/05/11  23:23
 * @Description 处理品牌业务的实现类
 * @Version 1.0
 */
@Slf4j
@Service
public class BrandServiceImpl implements BrandService {

    @Value("${csmall.crud.default-query-page-size}")
    private Integer defaultQueryPageSize;

    @Autowired
    private BrandRepository brandRepository;

    @Autowired
    private BrandCategoryRepository brandCategoryRepository;

    @Autowired
    private SpuRepository spuRepository;

    public BrandServiceImpl() {
        log.info("创建业务对象：BrandServiceImpl");
    }

    @Override
    public void addNew(BrandAddNewParam brandAddNewParam) {
        log.debug("开始处理【新增品牌】业务，参数：{}", brandAddNewParam);

        // 检查品牌名称是否被占用，如果被占用，则抛出异常
        String name = brandAddNewParam.getName();
        int count = brandRepository.countByName(name);
        log.debug("根据品牌名称统计匹配的品牌数量，结果：{}", count);
        if (count > 0) {
            String message = "新增品牌失败，品牌名称【" + name + "】已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 将属性模板数据写入到数据库中
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandAddNewParam, brand);
        brand.setGmtCreate(LocalDateTime.now());
        brand.setGmtModified(LocalDateTime.now());
        int rows = brandRepository.insert(brand);
        if (rows != 1) {
            String message = "新增品牌失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的品牌数据写入到数据库，完成！");
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【删除品牌】业务，参数：{}", id);

        //检查尝试删除的数据是否存在
        Object queryResult = brandRepository.getStandardById(id);
        log.debug("根据品牌ID统计匹配的品牌数量，结果：{}", queryResult);
        if (queryResult == null) {
            String message = "删除品牌失败，尝试删除的品牌数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 检查是否有类别关联到了此品牌，如果有，则抛出异常
        int categoryCount = brandCategoryRepository.countByBrandId(id);
        log.debug("根据品牌ID统计匹配的类别与品牌的关联数量，结果：{}", categoryCount);
        if (categoryCount > 0) {
            String message = "删除品牌失败，仍有类别与品牌的关联关联到此品牌！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查是否有SPU关联到了此品牌，如果有，则抛出异常
        int spuCount = spuRepository.countByBrandId(id);
        log.debug("根据品牌ID统计匹配的spu数量，结果：{}", spuCount);
        if (spuCount > 0) {
            String message = "删除品牌失败，仍有spu关联到此品牌！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //执行删除
        log.debug("即将执行删除数据，参数：{}", id);
        int rows = brandRepository.deleteById(id);
        if (rows != 1) {
            String message = "删除品牌失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void updateInfoById(Long id, BrandUpdateInfoParam brandUpdateInfoParam) {
        log.debug("开始处理【修改品牌详情】业务，参数ID：{}， 新数据：{}", id, brandUpdateInfoParam);

        //检查名称是否被占用
        int count = brandRepository.countByNameAndNotId(id, brandUpdateInfoParam.getName());
        if (count > 0) {
            String message = "修改详情失败，品牌名称已被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        //判断数据是否存在
        BrandStandardVO queryResult = brandRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "修改品牌详情失败，尝试修改的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        //执行修改
        Brand brand = new Brand();
        BeanUtils.copyProperties(brandUpdateInfoParam, brand);
        brand.setId(id);
        brand.setGmtModified(LocalDateTime.now());

        log.debug("即将修改数据：{}", brand);
        int rows = brandRepository.update(brand);
        if (rows != 1) {
            String message = "修改品牌详情失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public BrandStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询品牌详情】的业务，参数：{}", id);
        BrandStandardVO queryResult = brandRepository.getStandardById(id);
        if (queryResult == null) {
            String message = "根据id查询品牌详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("即将返回品牌详情：{}", queryResult);
        return queryResult;
    }

    @Override
    public PageData<BrandListItemVO> list(Integer pageNum) {
        return null;
    }

    @Override
    public PageData<AlbumListItemVO> list(Integer pageNum, Integer pageSize) {
        return null;
    }
}
